package com.spaceobj.chess.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.spaceobj.chess.handler.GameServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class NettyServer {

    @Autowired
    private ServerBootstrap serverBootstrap;

    @Autowired
    private GameServerHandler gameServerHandler;

    private ChannelFuture channelFuture;

    @PostConstruct
    public void start() throws Exception {
        try {
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(gameServerHandler);
                }
            });

            channelFuture = serverBootstrap.bind(8888).sync();
            log.info("Netty server started on port 8888");
        } catch (Exception e) {
            log.error("Failed to start Netty server", e);
            throw e;
        }
    }

    @PreDestroy
    public void stop() {
        if (channelFuture != null) {
            channelFuture.channel().close();
            channelFuture = null;
        }
    }
} 